package me.yiyou.meihua.ui.page.study

import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import me.yiyou.meihua.R
import me.yiyou.meihua.element.CustomButton
import me.yiyou.meihua.utils.LogUtil

@Composable
fun StudyPage() {

    val viewModel = StudyViewModel()

    // 异步加载数据
    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            viewModel.loadGuaData()
        }
    }

    // UI 状态管理
    val guaList by viewModel.guaList
    val isLoading by viewModel.isLoading
    val error by viewModel.error
    val questionIndex by viewModel.currentIndex     // 题目下标
    val inputContent by viewModel.inputContent // 输入的卦名
    val showExplain by viewModel.showExplain // 输入的卦名

    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .systemBarsPadding()
    ) {
        item {
            when {
                // 根据状态加载不同的页面
                isLoading -> {
                    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                        Text(text = "加载中...")
                    }
                }

                error != null -> {
                    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                        Text(text = error!!, color = Color.Red)
                    }
                }

                guaList?.isNotEmpty() == true -> {
                    val currentGua = guaList!![questionIndex]
                    Row(
                        Modifier
                            .padding(start = 16.dp, top = 16.dp)
                            .fillMaxWidth()
                            .height(80.dp),
                        horizontalArrangement = Arrangement.Center
                    ) {
                        Column {
                            structPartUp(title = currentGua.shang)
                            Spacer(modifier = Modifier.size(4.dp))
                            structPartDown(title = currentGua.xia)
                        }
                        Spacer(modifier = Modifier.width(26.dp))
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(top = 6.dp),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            val focusManager = LocalFocusManager.current
                            OutlinedTextField(
                                value = inputContent,
                                onValueChange = { viewModel.onInputChanged(it) }, // 输入变化监听
                                label = { Text("卦名") }, // 浮动标签
                                placeholder = { Text("请输入卦名") }, // 占位符
                                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Go),
                                keyboardActions = KeyboardActions(
                                    onSearch = {
                                        viewModel.checkAnswer(inputContent)
                                        focusManager.clearFocus() // 收起键盘
                                    }
                                ),
                                modifier = Modifier.width(160.dp)
                            )
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally,
                                verticalArrangement = Arrangement.Center,
                                modifier = Modifier.fillMaxHeight()
                            ) {
                                Image(
                                    painter = painterResource(R.drawable.icon_tip),
                                    contentDescription = "提示",
                                    modifier = Modifier
                                        .padding(start = 8.dp, end = 8.dp)
                                        .align(Alignment.CenterHorizontally)
                                        .size(26.dp)
                                        .clickable { viewModel.toggleExplain() }
                                )
                                Text(
                                    text = "提示",
                                    fontSize = 12.sp,
                                    modifier = Modifier
                                        .padding(start = 8.dp, end = 8.dp)
                                        .align(Alignment.CenterHorizontally),
                                    fontWeight = FontWeight.Bold
                                )
                            }
                        }
                    }
                    Row(
                        Modifier
                            .padding(top = 10.dp)
                            .fillMaxWidth()
                            .height(200.dp),
                        horizontalArrangement = Arrangement.Center
                    ) {
                        if (showExplain) {
                            Text(
                                text = currentGua.explain,
                                fontSize = 14.sp,
                                color = Color.Gray,
                                modifier = Modifier.padding(horizontal = 12.dp),
                                fontWeight = FontWeight.Bold
                            )
                        }
                    }
                }

                else -> {
                    LogUtil.e("TAG", "MemoryPage: GuaList is Null!")
                }
            }
            Row(
                modifier = Modifier
                    .padding(top = 16.dp)
                    .fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.Center
            ) {
                // 下一个按钮
                CustomButton(
                    text = "下一个",
                    onClick = { viewModel.onNextQuestion() },
                    modifier = Modifier.width(100.dp)
                )
                // 分割
                Spacer(modifier = Modifier.width(16.dp))
                // 提交按钮
                CustomButton(
                    text = "提交",
                    onClick = { viewModel.checkAnswer(inputContent) },
                    modifier = Modifier.width(100.dp)
                )
            }

        }

    }
}

/**
 * 上卦部分
 * 图根据穿过来的文字展示
 */
@Composable
fun structPartUp(title: String) {
    Row(verticalAlignment = Alignment.CenterVertically) {
        Text("上卦:", fontSize = 16.sp)
        Text(title, fontSize = 16.sp, modifier = Modifier.padding(start = 4.dp))
        Image(
            painter = painterResource(getGuaPicByName(title)),
            contentDescription = title,
            modifier = Modifier
                .size(40.dp)
                .padding(start = 8.dp)
        )
    }
}

/**
 * 下卦部分
 */
@Composable
fun structPartDown(title: String) {
    Row(verticalAlignment = Alignment.CenterVertically) {
        Text("下卦:", fontSize = 16.sp)
        Text(title, fontSize = 16.sp, modifier = Modifier.padding(start = 4.dp))
        Image(
            painter = painterResource(getGuaPicByName(title)),
            contentDescription = title,
            modifier = Modifier
                .size(40.dp)
                .padding(start = 8.dp)
        )
    }
}

/**
 * 根据卦名获取卦象
 */
fun getGuaPicByName(name: String): Int {
    return when (name) {
        "乾" -> R.drawable.g_qian
        "坤" -> R.drawable.g_kun
        "震" -> R.drawable.g_zhen
        "巽" -> R.drawable.g_xun
        "坎" -> R.drawable.g_kan
        "离" -> R.drawable.g_li
        "艮" -> R.drawable.g_gen
        "兑" -> R.drawable.g_dui
        else -> R.drawable.g_qian
    }
}